<template>
    <div>
    <basic-container>
      <avue-crud
        :option="tableOption"
        :data="tableData"
        :table-loading="tableLoading"
        :page="page"
        ref="crud"        
        v-model="formData"
        @row-save="handleSave"
        @row-del="handleDel"
        @refresh-change="handleRefreshChange"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :beforeOpen="handleBeforeOpen"
        @selection-change="handleSelectionChange"
        @row-update="handleUpdate"
        @search-change="handleSearchChange"
      >
      <template slot-scope="scope" slot="menu">
           <el-button
            type="text"
            @click.stop="handleShowIntro(scope.row)"
            icon="el-icon-view"
            size="mini"
            >活动详情</el-button>
             <el-button
            type="text"
            @click.stop="handleResolve(scope.row)"
            icon="el-icon-edit"
            size="mini"
            v-if="scope.row.status == 1"
            v-perm="'/admin/video-topic/check'"
          >审核通过</el-button>
          <el-button
            type="text"
            @click.stop="handleReject(scope.row)"
            icon="el-icon-edit"
            size="mini"
            v-if="scope.row.status == 1"
            v-perm="'/admin/video-topic/check'"
          >审核拒绝</el-button>
      </template>
      <template slot="videoChannelIdForm">
        <div>
            <div v-if="formData.videoChannelName">
              <div>
                直播间名称：{{ formData.videoChannelName }}  
              </div>
              <div>
                直播间编号：{{ formData.videoChannelNo }}  
              </div>
              <div>
                主播名称：{{ formData.anchor }}  
              </div>
            </div>
            
            <el-button
              type="primary"
              @click="handleSelectVideoChannel"
              icon="el-icon-edit"
              size="small"
              >选择直播频道</el-button>
          </div>
      </template>
      <template slot="menuLeft">
        
        <el-button
          type="danger"
          @click="handleBathDelRows"
          :loading="bachDeleting"
          v-perm="'/admin/video-topic/delete-by-ids'"
          icon="el-icon-remove"
          size="small"
        >批量删除</el-button>

        <el-button
            type="primary"
            @click="handleBathResolve"
            icon="el-icon-edit"
            v-perm="'/admin/video-topic/batch-check'"
            size="small"
          >批量审核通过</el-button>
          <el-button
            type="danger"
            @click="handleBathReject"
            icon="el-icon-edit"
            v-perm="'/admin/video-topic/batch-check'"
            size="small"
          >批量审核拒绝</el-button>

        <el-button
        type="primary"
        @click="handleExport"
        :loading="downloadLoading"
        icon="el-icon-download"
        v-perm="'/admin/video-topic/export'"
        size="small"
      >导出</el-button>
      </template>
      </avue-crud>
      </basic-container>
      <el-dialog :visible.sync="videoChannelDetailViewShowed" width="900px" title="话题活动详情">
          <div v-html="topicDesc"></div>
      </el-dialog>
      <el-dialog title="直播频道列表" width="1000px" :visible.sync="videoChannelSelectDialogShowed">
        <videoChannelComponent is-select @onSelectVideoChannel="handleOnSelectVideoChannel" />
      </el-dialog>
    </div>
  </template>
  <script>
  import { validatenull } from "@/util/validate";
  // import { DIC } from "@/const/dic";
  import {  getLabelFromDicV2 } from "@/const/dic";
  import { nowDate } from "../../util/date";
  import * as apiObj from "../../api/videoTopic";
  import { videoTopicTableOption} from "@/const/videoTopic/videoTopicTableOption.js";
  import videoChannelComponent from "../videoChannel/index";
  export default {
    components:{
      videoChannelComponent
    },
    data() {
      return {
        bachDeleting: false,
        tableOption: {}, //表格设置属性
        tableData: [], //表格的数据
        topicDesc:'',
        formData:{
            videoChannelName:'',
            videoChannelNo:'',
            anchor:''
        },
        downloadLoading:false,
        videoChannelSelectDialogShowed:false,
        videoChannelDetailViewShowed:false,
        tableLoading: false,
        tableQueryParam: {},
        page: {
          total: 0, //总页数
          currentPage: 1, //当前页数
          pageSize: 10 //每页显示多少条
        }
      };
    },
    created() {
      //初始化数据格式
      this.tableOption = videoTopicTableOption;
      this.handleList();
    },
    methods: {
      handleBathResolve() {
      if (
        !this.currentSelectedRowIds ||
        this.currentSelectedRowIds.length == 0
      ) {
        this.showError("请选择至少一条记录");
        return;
      }
      const ids = this.currentSelectedRowIds.filter(el=>el.status == 1).map(el=>el.id);
      if(!ids.length) {
        this.showError("请选择至少一条待审核记录");
        return;
      }
      this.$prompt('确认审核通过所选话题吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder:'审核备注'
        }).then(({ value }) => {
            value = value || '';
            apiObj.batchCheckRealAuth({
              ids,
              checkStatus:10,
              remark:value.trim()
          }).then(() => {
            this.success();
            this.handleList();
          });
          this.success();
        }).catch(() => {
          
        });
    },
    handleBathReject() {
      if (
        !this.currentSelectedRowIds ||
        this.currentSelectedRowIds.length == 0
      ) {
        this.showError("请选择至少一条记录");
        return;
      }
      const ids = this.currentSelectedRowIds.filter(el=>el.status == 1).map(el=>el.id);
      if(!ids.length) {
        this.showError("请选择至少一条待审核记录");
        return;
      }
      this.$prompt('确认审核拒绝所选话题吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder:'审核备注'
        }).then(({ value }) => {
            value = value || '';
            apiObj.batchCheckRealAuth({
              ids,
              checkStatus:5,
              remark:value.trim()
          }).then(() => {
            this.success();
            this.handleList();
          });
          this.success();
        }).catch(() => {
          
        });
    },
      handleOnSelectVideoChannel(item){
        this.videoChannelSelectDialogShowed = false;
        this.formData.videoChannelName = item.channelName;
        this.formData.videoChannelNo = item.channelNo;
        this.formData.videoChannelId = item.id;
        this.formData.anchor = item.realName;
      },
      handleSelectVideoChannel(){
        this.videoChannelSelectDialogShowed = true;
      },
      handleCurrentChange(page) {
        this.page.currentPage = page;
        this.handleList();
      },
      handleSizeChange(size) {
        this.page.pageSize = size;
        this.handleList();
      },
    handleResolve(row) {
      this.$prompt('确认审核通过吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder:'审核备注'
        }).then(({ value }) => {
            value = value || '';
            apiObj.checkRealAuth({
              id:row.id,
              checkStatus:10,
              remark:value.trim()
          }).then(() => {
            this.success();
            this.handleList();
          });
          this.success();
        }).catch(() => {
          
        });
    },
    handleReject(row) {
      this.$prompt('确认审核通过吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder:'审核备注'
        }).then(({ value }) => {
            value = value || '';
            apiObj.checkRealAuth({
              id:row.id,
              checkStatus:5,
              remark:value.trim()
          }).then(() => {
            this.success();
            this.handleList();
          });
          this.success();
        }).catch(() => {
          
        });
    },
    handleBathDelRows() {
        if (validatenull(this.currentSelectedRowIds)) {
          this.$notify({
            showClose: true,
            message: "请至少选择一行要删除的数据",
            type: "error"
          });
          return false;
        }
        this.$confirm('是否确认删除所选择记录吗', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.bachDeleting = true;
          apiObj.removeByIds(
            this.currentSelectedRowIds.map(el=>el.id)
          ).then(() => {
              this.bachDeleting = false;
              this.handleList();
              this.$message({
                showClose: true,
                message: "成功",
                type: "success"
              });
              this.$refs.crud.selectClear();
            })
            .catch(() => {
              this.bachDeleting = false;
            });
        });
      },
      handleShowIntro(row){
        apiObj.detail(row.id).then(({topicDesc})=>{
            this.topicDesc = topicDesc;
        });
        this.videoChannelDetailViewShowed = true;
      },
      handleSelectionChange(args) {
        this.currentSelectedRowIds = args;
      },
      handleSearchChange(params) {
        this.tableQueryParam = params;
        this.handleList();
      },
      handleBeforeOpen(callback,box){
        if(box == 'edit'){
          apiObj.detail(this.formData.id).then(({topicDesc})=>{
              this.formData.topicDesc = topicDesc;
          });
        }
        callback();
      },
      /**
       * @title 数据更新
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       * @param done 为表单关闭函数
       *
       **/
      handleUpdate(row, index, done, reject) {
        apiObj.update(row)
          .then(() => {
            this.handleList();
            this.$message({
              showClose: true,
              message: "修改成功",
              type: "success"
            });
            done();
          })
          .catch(() => {
            reject();
          });
      },      
      
      /**
       * @title 数据添加
       * @param row 为当前的数据
       * @param done 为表单关闭函数
       *
       **/
      handleSave(row, done, reject) {
        apiObj.create(row)
          .then(() => {
            this.handleList();
            this.$message({
              showClose: true,
              message: "添加成功",
              type: "success"
            });
            done();
          })
          .catch(() => {
            reject();
          });
      },
      handleRefreshChange() {
        this.handleList();
      },
      /**
       * @title 获取数据
       * @detail 赋值为tableData表格即可
       *
       **/
      handleList() {
        this.tableLoading = true;
        apiObj.list({
          pageNo: this.page.currentPage,
          pageSize: this.page.pageSize,
          ...this.tableQueryParam
        })
          .then(data => {
            this.tableData = data.data || data.dataList || [];
            this.page.total = data.total;
            this.tableLoading = false;
          })
          .catch(() => {
            this.tableLoading = false;
          });
      },     
      
      handleDel(row, index) {
        this.$confirm('是否确认删除', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            apiObj.removeById(
              row.id
            ).then(() => {
              this.handleList();
              this.$message({
                showClose: true,
                message: "删除成功",
                type: "success"
              });
              this.$refs.crud.selectClear();
            });
          })
          .catch(() => {});
      },    
      handleExport() {
        this.downloadLoading = true;
        apiObj.list({
          pageNo: 1,
          pageSize: 3000,
          ...this.tableQueryParam
        }).then(res => {
          import("@/vendor/Export2Excel").then(excel => {
            const tHeader = ["话题状态","话题编号","话题标题","开始时间","直播间名称","直播间编号","主播名称","话题分类","直播横竖屏类型","直播类型","活动介绍","是否推荐话题","排序值","审核备注","创建时间","创建人","修改时间","修改人"];
            const filterVal = ["status","topicNo","title","startTime","videoChannelName","videoChannelNo","anchor","categoryId","screenType","videoType","topicDesc","recommendFlag","sort","checkRemark","createTime","creator","modifyTime","modifier"];
            const data = this.formatJson(filterVal, res.data || res.dataList);
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: "直播话题" + nowDate()
            });
            this.downloadLoading = false;
          });
        });
      },
      formatJson(filterVal, jsonData) {      
        return jsonData.map(v =>
          filterVal.map(j => {
            return getLabelFromDicV2(this.$refs.crud.DIC,j,v[j]);
          })
        );
      }
    }
  };
  </script>
